<?php
namespace app\index\controller;

\think\Loader::import('controller/Jump', TRAIT_PATH, EXT);
use app\index\Controller;
use think\Db;
use think\Session;
use think\Cookie;

class Index extends Controller
{
    use \traits\controller\Jump;
    public function __construct()
    {
        parent::__construct();
//		$this->footer();
        $action = $this->request->action();
        $this->view->assign("action", $action);
        if (!method_exists($this, $action)) {
            die( $this->view->fetch($action));
        }
    }
    //获取code
    public function getcode(){
        $appId = WXAPPID;
        $urls = urlencode('http://tour.mgtvshop.com/index/index/index');
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appId."&redirect_uri=".$urls."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";

        header("location:".$url);
    }

    public function index()
    {
        //获取用户apenid
        $code = $_GET['code'];
        vendor ( 'ThirdLogin.WxLogin' );
        $appId = WXAPPID;
        $appKey = WXAPPKEY;
        $wx = new \WxLogin($appId,$appKey,$code);
        //得到access_token验证值
        $accessToken = $wx->getToken();
        if(!$accessToken){
            //$this->success('', '/index/index/getcode');
        }
        //得到用户的openid(登陆用户的识别码)和Client_id
        $openId = $wx->getOpenId();
        $arr['openid'] = $openId;
        $user = Db::table("tp_user")->where($arr)->find();
        if($user){
            Session::set('id',$user['id']);
            Session::set('openId',$openId);
        }

        $user_id = Session::get('id');

        /*首页轮播图*/
        $pic = Db::table("tp_indexpic")->where(array('isdelete'=>0))->select();
        //分类
        $cate_info = Db::table('tp_category')->where(array("isdelete"=>0))->select();

        //vip置顶开始时间
        $time = time() - TOPTIME;
        $whereOr = "`u`.`is_vip` = 1 AND `i`.`create_time` > {$time} AND `i`.`cate_id` = 1";
        $city_info = Db::table("tp_info")->alias("i")
            ->join("tp_user u","u.id = i.user_id","left")
            ->join("tp_category c","i.cate_id = c.id","left")
            ->field("i.*,u.img,u.id as uid,u.name,u.age,u.is_rz,u.sex,u.tel,u.is_vip")
            ->where("i.cate_id = 1 and i.isdelete = 0")
            ->whereOr($whereOr)
            ->order(['u.is_vip'=>'desc','i.create_time'=>'desc'])
            ->select();
//echo Db::table("tp_info")->getLastSql();exit;

        $whereGame = "`u`.`is_vip` = 1 AND `i`.`create_time` > {$time} AND `i`.`cate_id` = 4 AND `i`.`end_time` > ".time();
        $game_info = Db::table("tp_info")->alias("i")
            ->join("tp_user u","u.id = i.user_id","left")
            ->join("tp_category c","i.cate_id = c.id","left")
            ->field("i.*,u.img,u.id as uid,u.name,u.age,u.is_rz,u.sex,u.tel,u.is_vip")
            ->where("i.cate_id = 2 and i.isdelete = 0")
            ->whereOr($whereGame)
            ->order('i.create_time desc')
            ->select();
//        echo Db::table("tp_info")->getLastSql();exit;

        $whereis = "`u`.`is_vip` = 1 AND `i`.`create_time` > {$time} AND `i`.`cate_id` = 3 AND `i`.`end_time` > ".time();
        $tour_info = Db::table("tp_info")->alias("i")
            ->join("tp_user u","u.id = i.user_id","left")
            ->join("tp_category c","i.cate_id = c.id","left")
            ->field("i.*,u.img,u.id as uid,u.name,u.age,u.is_rz,u.sex,u.tel,u.is_vip")
            ->where("i.cate_id = 3 and i.isdelete = 0")
            ->whereOr($whereis)
            ->order('i.create_time desc')
            ->select();
//		echo Db::table('tp_info')->getLastSql();exit;

        //同城
        foreach($city_info as $k => $v){
            Db::table("tp_tag")->select($city_info[$k]['tag_id']);
//            echo Db::table('tp_comment')->getLastSql();exit;

            if($v){
                $city_info[$k]['create_time'] = date("m-d H:i",$v['create_time']);
                $city_info[$k]['go_time'] = date("m月d日",$v['go_time']);
                $city_info[$k]['comment_count'] = Db::table('tp_comment')->where(array('active_id'=>$v['id']))->count();
                $str=$v['address'];
                if(mb_strlen($str,'utf-8')>18){
                    $city_info[$k]['address']=mb_substr($str,0,18,'utf-8').'...';
                }else{
                    $city_info[$k]['address'] = $v['address'];
                }

                //标签处理
                $city_info[$k]['tag_id'] = Db::table("tp_tag")->select($city_info[$k]['tag_id']);
                if($v['other_tag'] != "") {
                    $arrq = explode(",", $v['other_tag']);
                    $arrw = array();
                    foreach ($arrq as $r => $t) {
                        $a = $r + 100;
                        $arrw[$r]['id'] = $a;
                        $arrw[$r]['tag'] = $t;
                    }

                    foreach ($arrw as $u => $o) {
                        $city_info[$k]['tag_id'][] = $arrw[$u];
                    }
                }
            }
        }

        //旅游
        foreach($tour_info as $k => $v){

            if($v){
                $tour_info[$k]['create_time'] = date("m-d H:i",$v['create_time']);
                $tour_info[$k]['go_time'] = date("m月d日",$v['go_time']);
                $tour_info[$k]['comment_count'] = Db::table('tp_comment')->where(array('active_id'=>$v['id']))->count();
                $str=$v['address'];
                if(mb_strlen($str,'utf-8')>18){
                    $tour_info[$k]['address']=mb_substr($str,0,18,'utf-8').'...';
                }else{
                    $tour_info[$k]['address'] = $v['address'];
                }

                /*$photo = $v['photo'];
                $tour_photo_arr = explode("|",$photo);
                $this->view->assign("tour_photo",$tour_photo_arr);*/
                //标签处理
                $tour_info[$k]['tag_id'] = Db::table("tp_tag")->select($tour_info[$k]['tag_id']);


                if($v['other_tag'] != "") {
                    $arr = explode(",", $v['other_tag']);
                    $arr1 = array();
                    foreach ($arr as $r => $t) {
                        $a = $r + 100;
                        $arr1[$r]['id'] = $a;
                        $arr1[$r]['tag'] = $t;
                    }

                    foreach ($arr1 as $u => $o) {
                        $tour_info[$k]['tag_id'][] = $arr1[$u];

                    }
                }
            }
        }

        //电竞邀约
        foreach($game_info as $k => $v){
            if($v){
                $game_info[$k]['create_time'] = date("m-d H:i",$v['create_time']);
                $game_info[$k]['go_time'] = date("m月d日",$v['go_time']);
                $game_info[$k]['comment_count'] = Db::table('tp_comment')->where(array('active_id'=>$v['id']))->count();
                $str=$v['address'];
                if(mb_strlen($str,'utf-8')>18){
                    $game_info[$k]['address']=mb_substr($str,0,18,'utf-8').'...';
                }else{
                    $game_info[$k]['address'] = $v['address'];
                }

                //标签处理
                $game_info[$k]['tag_id'] = Db::table("tp_tag")->select($game_info[$k]['tag_id']);


                if($v['other_tag'] != "") {
                    $arr = explode(",", $v['other_tag']);
                    $arr1 = array();
                    foreach ($arr as $r => $t) {
                        $a = $r + 100;
                        $arr1[$r]['id'] = $a;
                        $arr1[$r]['tag'] = $t;
                    }

                    foreach ($arr1 as $u => $o) {
                        $game_info[$k]['tag_id'][] = $arr1[$u];

                    }
                }
            }
        }

        /*是否有新消息		start*/
        $start_count = Db::table('tp_offered')->where(array('user_id'=>$user_id,'is_start'=>1,'is_true'=>0))->count();//某用户参加的活动是否开始

        $count = Db::table("tp_apply")->where(array('user_id'=>$user_id,'status'=>0))->count();//是否有人申请参团

        $map['q.is_true'] = 0;
        $map['i.isdelete'] = 0;
        $map['i.user_id'] = $user_id;
        $quit_count = Db::table('tp_quit')->alias('q')->join('tp_info i','q.active_id = i.id','left')->where($map)->count();//是否有人申请退出

        $quit_map['is_true'] = ['<>',0];
        $quit_map['user_id'] = $user_id;
        $quit_count2 = Db::table('tp_quit')->where($quit_map)->count();//通知退出参团申请人审核结果

        $report_count = Db::table('tp_offered')->alias('o')
            ->join('tp_info i','o.active_id = i.id','left')
            ->where(array('o.is_report'=>1,'i.user_id'=>$user_id))
            ->count();//某发起人的活动是否被举报
        /*是否有新消息		end*/

        /*升级vip start*/
//		$sql = "update tp_user set is_vip = 1 where money>=200";
//		Db::execute($sql);
        Db::table('tp_user')->where('money','>=',200)->setField('is_vip',1);
        /*升级vip end*/
        //判断今日是否已经签到
        $qiandao_info = Db::table('tp_user')->where('id',$user_id)->find();

        //var_dump($tour_info);exit;
//        $this->view->assign('next_day',$next_day?$next_day:0);
        $this->view->assign('qiandao',$qiandao_info['is_qiandao']?$qiandao_info['is_qiandao']:0);//0未签到，1已签到
        $this->view->assign('city_info',$city_info);
        $this->view->assign('game_info',$game_info);
        $this->view->assign('tour_info',$tour_info);


        $this->view->assign('pic',$pic);
        $this->view->assign('cate_info',$cate_info);
        $this->view->assign('user_id',$user_id?$user_id:0);
        $this->view->assign('count',$count);
        $this->view->assign('start_count',$start_count);
        $this->view->assign('quit_count',$quit_count);
        $this->view->assign('quit_count2',$quit_count2);
        $this->view->assign('report_count',$report_count);

        return $this->view->fetch();
    }

    /*
	 *查找一条数据的标签
	 */
    public function onetag(){
        $id = $_POST['id'];
        $cate = $_POST['cate'];
        $tour_info = Db::table("tp_info")->alias("i")
            ->field("i.tag_id,i.other_tag")
            ->where(array("i.cate_id"=>$cate,"i.isdelete"=>0,"i.id"=>$id))
            ->find();
        if($tour_info){
            /*  $tour_info[$k]['create_time'] = date("m-d H:i",$v['create_time']);
              $tour_info[$k]['go_time'] = date("m月d日",$v['go_time']);
              $tour_info[$k]['comment_count'] = Db::table('tp_comment')->where(array('active_id'=>$v['id']))->count();*/

            /*$photo = $v['photo'];
            $tour_photo_arr = explode("|",$photo);
            $this->view->assign("tour_photo",$tour_photo_arr);*/
            //标签处理
            $tour_info['tag_id'] = Db::table("tp_tag")->select($tour_info['tag_id']);


            if($tour_info['other_tag'] != "") {
                $arr = explode(",", $tour_info['other_tag']);
                $arr1 = array();
                foreach ($arr as $r => $t) {
                    $a = $r + 100;
                    $arr1[$r]['id'] = $a;
                    $arr1[$r]['tag'] = $t;
                }
                foreach ($arr1 as $u => $o) {
                    $tour_info['tag_id'][] = $arr1[$u];

                }
            }
        }
        return json_encode($tour_info['tag_id']);
    }

    /*
     *轮播图文章
     */
    public function article(){
        $id = $_GET['id'];
        $rand = rand(1,10);
        $article = Db::table('tp_indexpic')->where(array('id'=>$id))->find();
        Db::table('tp_indexpic')->where('id',$id)->setInc('count',$rand);
        $info['title'] = $article['title'];
        $info['create_time'] = date("Y-m-d",$article['create_time']);
        $info['pic'] = $article['pic'];
        $info['content'] = $article['content'];
        $info['count'] = $article['count'];

        $this->view->assign('article',$info);
        return $this->view->fetch();
    }
    /*
     *查看附近 
     */
    public function search_near(){
        $index_lng = Cookie::get('index_lng');//经度
        $index_lat = Cookie::get('index_lat');//经度
        //以下为核心代码
        if($index_lng != '' && $index_lat != ''){
            $range = 180 / pi() * 5 / 6372.797;     //里面的 1 就代表搜索 1km 之内，单位km
            $lngR = abs($range / cos($index_lat * pi() / 180));
            $maxLat = $index_lat + $range;//最大纬度
            $minLat = $index_lat - $range;//最小纬度
            $maxLng = $index_lng + $lngR;//最大经度
            $minLng = $index_lng - $lngR;//最小经度

            $map['i.isdelete'] = 0;
            $map['i.lat'] = array([ '>=', $minLat],[ '<=', $maxLat]);//范围判断纬度条件
            $map['i.lng'] = array([ '>=', $minLng],[ '<=', $maxLng]);//范围判断经度条件

            $info = Db::table("tp_info")->alias("i")
                ->join("tp_user u","u.id = i.user_id","left")
                ->join("tp_category c","i.cate_id = c.id","left")
                ->field("i.*,u.img,u.id as uid,u.name,u.age,u.is_rz,u.sex")
                ->where($map)
                ->order('i.create_time desc')
                ->select();

            foreach($info as $k => $v){
                if($v){
                    $info[$k]['create_time'] = date("m-d H:i",$v['create_time']);
                    $info[$k]['go_time'] = date("m月d日",$v['go_time']);
                    $info[$k]['comment_count'] = Db::table('tp_comment')->where(array('active_id'=>$v['id']))->count();
                    /*$photo = $v['photo'];
                    $photo_arr = explode("|",$photo);
                    $this->view->assign("photo",$photo_arr);*/
                    //标签处理
                    $info[$k]['tag_id'] = Db::table("tp_tag")->select($info[$k]['tag_id']);
                    if($v['other_tag'] != "") {
                        $arrq = explode(",", $v['other_tag']);
                        $arrw = array();
                        foreach ($arrq as $r => $t) {
                            $a = $r + 100;
                            $arrw[$r]['id'] = $a;
                            $arrw[$r]['tag'] = $t;
                        }

                        foreach ($arrw as $u => $o) {
                            $info[$k]['tag_id'][] = $arrw[$u];
                        }
                    }
                }
            }
        }
        $this->view->assign('info',$info);
        return $this->view->fetch();
    }

    public function detail(){
        $id = $_GET['id'];//活动
        $uid = $_GET['uid'];//活动发布者id
        $sid = Session::get('id')?Session::get('id'):0;

        /*查看是否已经关注此活动 start*/
        $gz_where['gz_id'] = $sid;
        $gz_where['info_id'] = $id;
        $info_gz = Db::table('tp_gz')->where($gz_where)->count();
        /*查看是否已经关注此活动 end*/

        /*查看是否已经申请活动 start*/
        $data['friend_id'] = $sid;
        $data['active_id'] = $id;
        $data['status'] = 0;//申请还未处理
        $data['type'] = 1;
        $is_apply = Db::table('tp_apply')->where($data)->count();

        $this->view->assign('is_apply',$is_apply);
        /*查看是否已经申请活动  end*/

        /*查看是否已经申请成功 start*/
        $info['friend_id'] = $sid;
        $info['active_id'] = $id;
        $info['status'] = 1;//申请还未处理
        $info['type'] = 1;
        $success_apply = Db::table('tp_apply')->where($info)->count();

        $this->view->assign('success_apply',$success_apply);
        /*查看是否已经申请成功 end*/

        /*查看是否存在退出此团申请 start*/
        $quit_map['is_true'] = ['<>','-1'];
        $quit_map['user_id'] = $sid;
        $quit_map['active_id'] = $id;
        $quit_count = Db::table('tp_quit')->where($quit_map)->count();

        $this->view->assign('quit_count',$quit_count);
        /*查看是否存在退出此团申请 end*/

        /*点击查看活动之后浏览刘加1*/
        $count_info = Db::table('tp_info')->field('count')->where(array('id'=>$id))->find();
        $count = $count_info['count']+1;

        /*将浏览者的信息记录到浏览记录表tp_look里面去*/
        $is_look = Db::table('tp_look')->where(array('user_id'=>$sid,'fabu_id'=>$uid,'isdelete'=>0))->count();
        if($is_look == 0){
            if($sid != $uid){
                $look_info['user_id'] = $sid;
                $look_info['fabu_id'] = $uid;
                $look_info['create_time'] = time();
                Db::table('tp_look')->insert($look_info);
            }
        }

        Db::table('tp_info')->where(array('id'=>$id))->setField('count',$count);
        $user_info = Db::table("tp_user")->where(array('id'=>$uid))->find();

        $detail_info = Db::table("tp_info")->where(array("id"=>$id))->find();

        //评论
        $comment = Db::table('tp_comment')->alias('c')
            ->field('c.content,c.create_time,c.type,c.num,c.gift_type,c.comment_id,u.img,u.name,u.sex,u.age,u2.name answer_name')
            ->join('tp_user u','c.comment_id = u.id','left')
            ->join('tp_user u2','c.answer_id = u2.id','left')
            ->where('active_id',$id)->order('create_time asc')->select();

        foreach($comment as $k => $v){
            $comment[$k]['create_time'] = date('m/d H:i',$v['create_time']);
        }
        $comment_count_map['active_id']  = ['=',$id];
        $comment_count_map['type'] = ['<>',3];
        $comment_count = Db::table('tp_comment')->where($comment_count_map)->count();//评论数

        /*某活动的参团人数*/
        $offered_count = Db::table("tp_offered")->where(array('active_id'=>$id))->count();
        $this->view->assign("user",$user_info);
        $this->view->assign("info_gz",$info_gz);
        $this->view->assign("comment",$comment);
        $this->view->assign("comment_count",$comment_count);
        $this->view->assign("info",$detail_info);
        $this->view->assign("id",$id);
        $this->view->assign("uid",$uid);
        $this->view->assign("user_id",$sid);
        $this->view->assign('offered_count',$offered_count);
        return $this->view->fetch();
    }
    public function message(){
        $user_id = Session::get('id');
        /*参团信息和加好友信息提示		start*/
        $field = "a.id as aid,a.create_time,u.name,a.friend_id,a.status,a.content,a.type";
        $apply = Db::table("tp_apply")->alias("a")
            ->join("tp_user u","a.friend_id = u.id","left")
            ->field($field)
            ->where(array("a.user_id"=>$user_id,"a.isdelete"=>0,"a.status"=>0))
            ->order("a.create_time desc")
            ->select();
        /*参团信息和加好友信息提示		end*/

        /*提醒活动参与者是否开始活动		start*/
        $sub_field = "o.user_id as uid,o.active_id,o.is_start,o.create_time,i.user_id";
        $subQuery = Db::table('tp_offered')->alias('o')
            ->join('tp_info i','o.active_id = i.id','left')
            ->field($sub_field)
            ->where(array('o.user_id'=>$user_id,'o.is_start'=>1,'o.is_true'=>0))
            ->buildSql();

        $start_field = "ot.*,u.name";
        $start_active = Db::table($subQuery.' ot')
            ->join('tp_user u','ot.user_id = u.id','left')
            ->field($start_field)
            ->order("ot.create_time desc")
            ->select();
        /*提醒活动参与者是否开始活动		end*/

        /*退出此团消息		start*/
        $quit_field = "q.*,u.name";
        $quitQuery = Db::table('tp_quit')->alias('q')
            ->join('tp_user u','q.user_id = u.id','left')
            ->field($quit_field)
            ->buildSql();

        $quit_field2 = "qu.*,i.user_id as uid";
        $quit = Db::table($quitQuery.' qu')
            ->join('tp_info i','i.id = qu.active_id','left')
            ->field($quit_field2)
            ->where('is_true',0)
            ->order("qu.create_time desc")
            ->select();
        /*退出此团消息		end*/

        /*活动发起者同意参团者的退出申请		start*/
        $res_map['user_id'] = $user_id;
        $res_map['is_true'] = ['<>',0];
        $res_quit = Db::table('tp_quit')->where($res_map)->select();
        /*活动发起者同意参团者的退出申请		end*/


        $data = array();
        foreach($apply as $k => $v){
            $data[$k]['aid'] = $v['aid'];
            $data[$k]['create_time'] = date("Y/m/d H:i",$v['create_time']);
            $data[$k]['name'] = $v['name'];
            $data[$k]['id'] = $v['friend_id'];
            $data[$k]['status'] = $v['status'];
            $data[$k]['content'] = $v['content'];
            $data[$k]['type'] = $v['type'];
        }

        $start_info = array();
        foreach($start_active as $k => $v){
            $start_info[$k]['active_id'] = $v['active_id'];
            $start_info[$k]['create_time'] = date("Y/m/d H:i",$v['create_time']);
            $start_info[$k]['name'] = $v['name'];
            $start_info[$k]['is_start'] = $v['is_start'];
            $start_info[$k]['user_id'] = $v['user_id'];//活动发布者id
            $start_info[$k]['uid'] = $v['uid'];//参与者id
        }

        $quit_info = array();
        foreach($quit as $k => $v){
            $quit_info[$k]['user_id'] = $v['user_id'];//参与者id
            $quit_info[$k]['active_id'] = $v['active_id'];
            $quit_info[$k]['create_time'] = date("Y/m/d H:i",$v['create_time']);
            $quit_info[$k]['name'] = $v['name'];
            $quit_info[$k]['is_true'] = $v['is_true'];
            $quit_info[$k]['reason'] = $v['reason'];
            $quit_info[$k]['uid'] = $v['uid'];//活动发布者id
        }

        /*活动被举报提示 start*/
        $report = Db::table('tp_offered')->alias('o')
            ->join('tp_info i','o.active_id = i.id','left')
            ->field('i.user_id,o.create_time,o.report_con')
            ->where(array('o.is_report'=>1))
            ->select();

        /*活动被举报提示 end*/

        $this->view->assign('report',$report);

        $this->view->assign('data',$data);
        $this->view->assign('start_info',$start_info);
        $this->view->assign('quit_info',$quit_info);
        $this->view->assign('res_quit',$res_quit);
        $this->view->assign('user_id',$user_id);
        return $this->view->fetch();
    }
    /*
     * 首页搜索
     * */
    public function search(){
        $like = $_GET['like'];
        $map['u.name']  = ['like',"%$like%"];
        $info = Db::table("tp_user")->alias('u')
            ->join('tp_friend f','u.id = f.user_id')
            ->where($map)->select();
        $this->view->assign("info",$info);
        return $this->view->fetch();
    }
    /*
     * 拒绝参团申请
     * */
    public function disagree(){
        $id = $_GET['id'];
        $aid = $_GET['aid'];
        $type = $_GET['type'];
        $info = Db::table('tp_apply')->alias('a')
            ->join('tp_info u','a.active_id = u.id','left')
            ->field("u.deposit")
            ->where(array('a.id'=>$aid))
            ->find();
        if($info['deposit'] == 0){
            $row = 1;
        }else{
            $sql = "update tp_user set money = money+{$info['deposit']} where id = {$id}";

            $row = Db::execute($sql);
        }

        $data['status'] = '-2';
        $data['isdelete'] = 1;
        $res = Db::table('tp_apply')
            ->where(array('id'=>$aid,'type'=>$type))
            ->update($data);
        if($res){
            echo "<script>alert('操作成功！');window.location.href='/index/index/index'</script>";
        }else{
            echo "<script>alert('操作失败！');window.location.href='/index/index/index'</script>";
        }
    }
    /*
     * 同意参团申请
     * */
    public function agree(){
        $uid = Session::get('id');//当前登录用户
        $aid = $_GET['aid'];//apply主键id
        $id = $_GET['id'];
        $data['status'] = 1;
        $data['isdelete'] = 1;
        $res = Db::table('tp_apply')
            ->where(array('id'=>$aid))
            ->update($data);
        $active = Db::table("tp_apply")->where(array('id'=>$aid))->find();
        if($res){
            $offered_data['user_id'] = $id;
            $offered_data['active_id'] = $active['active_id'];
            $offered_data['isdelete'] = 0;
            $res = Db::table('tp_offered')->insert($offered_data);

            if($res){
                echo "<script>alert('操作成功！');window.location.href='/index/index/index'</script>";
            }else{
                echo "<script>alert('操作失败！');window.location.href='/index/index/index'</script>";
            }

        }else{
            echo "<script>alert('操作失败！');window.location.href='/index/index/index'</script>";
        }
    }

    /*
     * 拒绝好友申请
     * */
    public function friend_disagree(){
        $aid = $_GET['aid'];//apply主键id

        $data['status'] = '-2';
        $data['isdelete'] = 1;
        $res = Db::table('tp_apply')
            ->where(array('id'=>$aid))
            ->update($data);
        if($res){
            echo "<script>alert('操作成功！');window.location.href='/index/index/index'</script>";
        }else{
            echo "<script>alert('操作失败！');window.location.href='/index/index/index'</script>";
        }
    }
    /*
     * 同意好友申请
     * */
    public function friend_agree(){
        $uid = Session::get('id');//当前登录用户
        $id = $_GET['id'];
        $aid = $_GET['aid'];//apply主键id

        $data['status'] = 1;
        $data['isdelete'] = 1;
        $res = Db::table('tp_apply')
            ->where(array('id'=>$aid))
            ->update($data);
        if($res){
            $data2['user_id'] = $uid;
            $data2['friend_id'] = $id;
            $result = Db::table('tp_friend')->insert($data2);

            if($result){
                echo "<script>alert('操作成功！');window.location.href='/index/index/index'</script>";
            }
        }else{
            echo "<script>alert('操作失败！');window.location.href='/index/index/index'</script>";
        }
    }

    public function index_search(){
        $like = $_POST['like'];

        $map['u.name']  = ['like',"%$like%"];
        $map['i.isdelete'] = 0;

        $like_info = Db::table("tp_info")->alias("i")
            ->join("tp_user u","u.id = i.user_id","left")
            ->join("tp_category c","i.cate_id = c.id","left")
            ->field("i.*,u.sex,u.img,u.id as uid,u.name,u.age,u.is_rz")
            ->where($map)
            ->select();
        return json_encode($like_info);
    }
    /*
	 * 关注
	 */
    public function dd(){
        $id = Session::get('id');
        $data['gz_id'] = $id?$id:0;//用户id
        if($id == 0){
            echo "-1";exit;
        }
        $data['info_id'] = $_POST['id'];
        $uid = $_POST['uid'];
        if($id == $uid){
            echo "0";exit;
        }
        $look = Db::table("tp_gz")->where($data)->select();
        if($look){
            echo "-2";exit;
        }
        $insert = Db::table("tp_gz")->insert($data);
        if($insert){
            echo "1";exit;
        }
    }

    /*
     * 申请参团
     * */
    public function addapply(){
        $data['user_id'] = $_POST['uid'];//发起人id
        $data['active_id'] = $_POST['id'];//活动id
        $deposit = $_POST['deposit'];//参团金额
        $id = Session::get('id')?Session::get('id'):0;
        $data['friend_id'] = $id;

        $data['create_time'] = time();
        $data['type'] = 1;

        $select['friend_id'] = $id;
        $select['active_id'] = $_POST['id'];//活动id

        $select = Db::table("tp_apply")->where($select)->select();

        if($select){
            echo "-2";exit;
        }else{
            //判断用户是否登录
            if($id>0){
                $rz = Db::table('tp_info')->where(array('id'=>$_POST['id']))->find();
                if($rz['only_rz'] == 1){
                    $user = Db::table('tp_user')->where(array('id'=>$id))->find();
                    if($user['is_rz'] != 1){
                        echo "-6";exit;
                    }
                }
                //用户已登录
                $is_time = Db::table('tp_info')->field('go_time')->where(array('id'=>$_POST['id']))->find();
                $go_time = $is_time['go_time'];
                if(time()<$go_time){
                    //用户金额大于参团费用可以报名，否则不能
                    $user_money = Db::table('tp_user')->field('money')->where('id',$id)->find();
                    $money = $user_money['money'];
                    $yue = $money-$deposit;

                    if($yue >= 0){
                        $yes = Db::table("tp_apply")->insert($data);

                        if($yes){
                            $info['money'] = $yue;
                            //var_dump($yue.','.$money);exit;
                            if($yue == $money){
                                $result = 1;
                            }else{
                                $result = Db::table('tp_user')->where('id',$id)->setField($info);
                            }
                            if($result){
                                echo "1";exit;
                            }
                        }
                    }else{
                        echo "-3";exit;
                    }
                }else{
                    //活动已开始，报名失败
                    echo "-4";exit;
                }
            }else{
                Session::set('url',$_SERVER['REQUEST_URI']);
                $info = [
                    'code' => '-5',
                    'active_id' => $_POST['id']
                ];
                return json_encode($info);
            }


        }
    }

    /*
     * 退出此团
     * */
    public function quit_active(){
        $data = $_POST;
        $data['create_time'] = time();

        $info['active_id'] = $_POST['active_id'];
        $info['user_id'] = $_POST['user_id'];
        $res = Db::table('tp_quit')->insert($data);
        if($res){
            return 1;
        }
    }
    /*
     *发布者同意参团者退出活动
     *1.将参团者参团所交押金存入参团者
     *2.将tp_offered表中的对应数据删除
     * */
    public function quit_agree(){
        $data = $_GET;
        $info['is_true'] = 1;
        $info['create_time'] = time();
        $res = Db::table('tp_quit')->where($data)->setField($info);

        if($res){
            $deposit_info = Db::table('tp_info')->field('deposit')->where('id',$_GET['active_id'])->find();
            $deposit = $deposit_info['deposit'];//参与者所交押金
            $user_info = Db::table('tp_user')->field('money')->where('id',$_GET['user_id'])->find();
            $money = $user_info['money'];
            $change_money = $money+$deposit;
            Db::table('tp_user')->where('id',$_GET['user_id'])->setField('money',$change_money);

            $Credit = OUT_CREDIT;//扣除积分
            $sql = "update tp_user set  Credit = Credit-{$Credit} where id = {$_GET['user_id']}";
            Db::execute($sql);

            Db::table('tp_offered')->where($data)->delete();

            echo "<script>alert('操作成功！');window.location.href='/index/index/index'</script>";
        }else{
            echo "<script>alert('操作失败！');window.location.href='/index/index/index'</script>";
        }
    }
    /*
     * 发布者拒绝参团者退出活动
     * */
    public function quit_disagree(){
        $data = $_GET;
        $info['is_true'] = -1;
        $info['create_time'] = time();
        $data['user_id'] = 1;
        $data['active_id'] = 101;
        $res = Db::table('tp_quit')->where($data)->setField($info);
        if($res){
            echo "<script>alert('操作成功！');window.location.href='/index/index/index'</script>";
        }else{
            echo "<script>alert('操作失败！');window.location.href='/index/index/index'</script>";
        }

    }

    public function search_result(){
        $user_id = Session::get('id');
        $tag_id = $_GET['tag_id'];
        if(true){
            //标签搜索
            $tag_id = $_GET["tag_id"];
            $field = "i.*,u.sex,u.img,u.id as uid,u.name,u.age,u.is_rz";
            $where['tag_id'] = array('like','%'.$tag_id.'%');
            $other['other_tag'] = array('like','%'.$tag_id.'%');
            $search_info = Db::table("tp_info")->alias("i")
                ->join("tp_user u","u.id = i.user_id","left")
                ->join("tp_category c","i.cate_id = c.id","left")
                ->field($field)
                ->where($where)
                ->whereOr($other)
                ->select();
            foreach($search_info as $k => $v){
                $search_info[$k]['create_time'] = date("m-d H:i",$v['create_time']);
                $search_info[$k]['go_time'] = date("m月d日",$v['go_time']);
                $search_info[$k]['comment_count'] = Db::table('tp_comment')->where(array('active_id'=>$v['id']))->count();

                //标签处理
                $search_info[$k]['tag_id'] = Db::table("tp_tag")->select($search_info[$k]['tag_id']);
                if($v['other_tag'] != "") {
                    $arrq = explode(",", $v['other_tag']);
                    $arrw = array();

                    foreach ($arrq as $r => $t) {
                        $a = $r + 100;
                        $arrw[$r]['id'] = $a;
                        $arrw[$r]['tag'] = $t;
                    }

                    foreach ($arrw as $u => $o) {
                        $search_info[$k]['tag_id'][] = $arrw[$u];
                    }

                }
            }

        }else{
            $data = $_GET['data'];
            $search_info = json_decode($data,true);
            foreach($search_info as $k => $v){
                $search_info[$k]['create_time'] = date("m-d H:i",$v['create_time']);
                $search_info[$k]['go_time'] = date("m月d日",$v['go_time']);
                $search_info[$k]['comment_count'] = Db::table('tp_comment')->where(array('active_id'=>$v['id']))->count();
                $search_info[$k]['tag_id'] = Db::table("tp_tag")->select($search_info[$k]['tag_id']);
            }
        }
        $this->view->assign('user_id',$user_id);
        $this->view->assign('search_info',$search_info);
        return $this->view->fetch();
    }
    /*
     * 判断用户是否完善个人信息
     * */
    public function person_message(){
        $id = Session::get('id')?Session::get('id'):0;
        if($id != 0){
            /*评论和回复时检测用户是否完善个人信息*/
            $info = Db::table("tp_user")->where(array("id"=>$id))->find();
            if($info['name'] != '' && $info['img'] != '' && $info['age'] != 0 && $info['tel'] != ''){
                return 1;//个人信息已完善
            }else{
                return json(['code' => -1,'msg' =>'请先完善个人信息再来评论或回复！（感叹号的为必填信息）']);
            }
        }else{
            return json(['code' => -2,'msg' =>'请先登录账号再来评论或回复！']);
        }
    }
    /*
     *评论时处于未登录状态处理 
     */
    public function after_login(){
        Session::set('url',$_SERVER['REQUEST_URI']);
        echo "<script>alert('您还未登录，请先登录！');window.location.href='/index/login/login_deng'</script>";
    }
    /*
     *评论
     */
    public function detail_pl(){
        $id = Session::get('id');
        $data = $_POST;
        $data['create_time'] = time();
        if($data['content'] != ''){
            $res = Db::table('tp_comment')->insert($data);
            if($res){
                $field = "c.content,c.create_time,c.comment_id,u.name,u.img,u.sex,u.age";
                $new = Db::table('tp_comment')->alias('c')
                    ->join('tp_user u','c.comment_id = u.id','left')
                    ->field($field)
                    ->order('c.id desc')
                    ->find();
                $new['create_time'] = date("m/d H:i",$new['create_time']);
                return json(['code' => 1, 'msg' => $new]);
            }
        }else{
            return json(['code' => -1,'msg' => '评论内容不能为空！']);
        }
    }
    /*
     * 回复
     */
    public function add_answer(){
        $data = $_POST;
        $data['type'] = 2;
        $data['create_time'] = time();
        if($data['content'] == ''){
            $res = Db::table('tp_comment')->insert($data);
            if(true){
                $field = "c.content,c.create_time,u.img,u.name,u.age,u.sex,u2.name as named,u2.id as id";
                $info = Db::table('tp_comment')->alias('c')
                    ->join('tp_user u','c.comment_id = u.id','left')
                    ->join('tp_user u2','c.answer_id = u2.id','left')
                    ->field($field)
                    ->order('create_time desc')
                    ->find();
                $info['create_time'] = date("m/d H:i",$info['create_time']);
                return json(['code' => 1,'msg' => $info]);
            }else{
                $info = [
                    'code' => -1
                ];
                return json_encode($info);
            }
        }else{
            return json(['code' => -2,'msg' =>'回复内容不能为空！']);
        }
    }
    public function comment_info($id){
        $comment_info = Db::table("tp_comment")->alias('c')
            ->join('tp_user u','c.friend_id = u.id','left')
            ->field('c.id,c.active_id,c.friend_id,c.create_time,c.content,u.name,u.img')
            ->where(array("c.active_id"=>$id))->select();
        return $comment_info;
    }

    /*
     * 活动参与者同意开始活动
     * */
    public function start_active_agree(){
        $uid = $_GET['user_id'];
        $active_id = $_GET['active_id'];

        $info = Db::table('tp_info')->field('go_time,is_start')->where('id',$active_id)->find();
        $go_time = $info['go_time'];
        $is_start = $info['is_start'];

        if(true){
            if(true){
                $end['is_end'] = 0;
                $end['button_status'] = 1;
                Db::table('tp_offered')->where(array("active_id"=>$active_id,'user_id'=>$uid))->update($end);

                $info = Db::table('tp_info')->field('user_id,deposit')->where('id',$active_id)->find();
                $user_id = $info['user_id'];//活动发布者id
                $deposit = $info['deposit'];//参团者押金

                $map['user_id'] = $uid;
                $map['active_id'] = $active_id;
                $start = Db::table('tp_offered')->where($map)->setField('is_true',1);
                if(true){
                    $user_money = Db::table('tp_user')->field('money')->where('id',$user_id)->find();
                    $money = $user_money['money'];//发布者余额
                    $change_money = $money+$deposit;
                    //同意之后将 参与者 参团时的押金转入活动发布者
                    Db::table('tp_user')->where('id',$user_id)->setField('money',$change_money);
                    echo "<script>alert('操作成功!');window.location.href='/index/index/index'</script>";
                }
            }else{
                echo "<script>alert('未到活动出行时间，操作失败!');window.location.href='/index/personal/offered?id=$uid';</script>";
            }
        }else{
            echo "<script>alert('活动发起人未点击开始活动，操作失败!');window.location.href='/index/personal/offered?id=$uid';</script>";
        }
    }
    /*
     * 参与者点击  我知道了
     * */
    public function kown(){
        $data = $_POST;
        $res = Db::table('tp_quit')->where($data)->delete();
        if($res){
            return 1;
        }
    }

    /*
     * 送花
     * */
    public function give_gift(){
        Db::startTrans();
        $flower = $_POST['flower'];
        $uid = $_POST['uid'];//活动发布者
        $sid = Session::get('id');//送礼人

        try{
            Db::table('tp_user')->where(array('id'=>$sid))->setDec('flower',$flower);//送礼人
            Db::table('tp_user')->where(array('id'=>$uid))->setInc('flower',$flower);//发布者
            Db::table('tp_user')->where(array('id'=>$sid))->setInc('asset',$flower*1);//送礼人财富值
            Db::table('tp_user')->where(array('id'=>$uid))->setInc('charm2',$flower*1);//发布者魅力值
            // 提交事务
            Db::commit();
            $info = array(
                'code' => 1,
                'msg' => '送花成功！'
            );
            return json_encode($info);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $info = array(
                'code' => 0,
                'msg' => '送花失败！'
            );
            return json_encode($info);
        }


    }
    public function send_gift(){
        Db::startTrans();
        $count = $_POST['count'];
        $gift_type = $_POST['gift_type'];
        $coins = $_POST['coins'];
        $uid = $_POST['uid'];//活动发布者
        $id = $_POST['id'];//活动id
        $sid = Session::get('id');//送礼人

        if($sid <= 0){
            Session::set('url',$_SERVER['REQUEST_URI']);
            $info = [
                'code' => '-5',
                'active_id' => $_POST['id']
            ];
            return json(['code' => '-5', 'msg' => $info]);exit;
        }

        try{
            Db::table('tp_user')->where(array('id'=>$sid))->setDec('coins',$coins);//送礼人
            Db::table('tp_user')->where(array('id'=>$uid))->setInc('coins',$coins*0.4);//发布者获得收到礼物的40%收益
            Db::table('tp_user')->where(array('id'=>$sid))->setInc('asset',$coins*1);//送礼人财富值
            Db::table('tp_user')->where(array('id'=>$uid))->setInc('charm',$coins*1);//发布者魅力值
            //送礼人信息
            $info = Db::table('tp_user')->field('name')->where(array('id'=>$sid))->find();

            //插入送礼数据信息
            $data['comment_id'] = $sid;
            $data['answer_id'] = $uid;
            $data['active_id'] = $id;
            $data['num'] = $count;
            $data['gift_type'] = $gift_type;
            $data['type'] = 3;//3为送礼
            $data['create_time'] = time();
            Db::table('tp_comment')->insert($data);

            $msg['name'] = $info['name'];
            $msg['count'] = $count;//数量
            $msg['gift_type'] = $gift_type;//礼物类型
            // 提交事务
            Db::commit();
            return json(['code' => 1, 'msg' => $msg ]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => '0', 'msg' => '拾友币不足，是否现在去充值！']);
        }

    }
}
